package com.example.demo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by wangyg6 on 2018/11/2.
 */
public class ClassUtils {
	static Logger logger = LoggerFactory.getLogger(ClassUtils.class);

	/**
	 * 指定基础包名及类名（不带路径）匹配模式，查找出匹配的类名（带路径）。
	 * @param basePackage
	 * @param classPattern
	 * @return
	 * @throws IOException
	 */
	public static List<String> findClassName(String basePackage, String classPattern) throws IOException {
		ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
		String basePackageWithResPath = org.springframework.util.ClassUtils.convertClassNameToResourcePath(basePackage);
		String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
				+ basePackageWithResPath + "/**/" + classPattern;
		Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
		List<String> classNameList = new LinkedList<String>();
		for(Resource res : resources){
			logger.debug(res.getURL().getPath());
			int index = res.getURL().getPath().indexOf(basePackageWithResPath);
			if(index >= 0){
				String classNamePath = res.getURL().getPath().substring(index);
				String className = org.springframework.util.ClassUtils.convertResourcePathToClassName(classNamePath);
				if(className.endsWith(".class")){
					className = className.substring(0, className.length()-6);
				}
				logger.debug("find class: " + className);
				classNameList.add(className);
			}

		}

		return classNameList;
	}
}
